<template>
    <pageTabelLayout>
        <template #pageHeader>
            <div class="search-form divClass" v-if="headerShow">
                <div>
                    <a-form size="small" :model="pageData" layout="inline">
                        <a-form-item label="拆纱工">
                            <!-- <a-select popup-container="html"  :style="{ width: '200px' }" :loading="loading" @search="handleSearch" class="bacClass"
                            v-model="pageData.empName" :filter-option="false" allow-search allow-clear
                            @focus="focusSel">
                            <a-option v-for="item in pageData.nameList" :value="item">{{ item }}</a-option>
                        </a-select> -->
                            <a-input allow-clear :style="{ width: '200px' }" class="bacClass" v-model="pageData.empName"
                                @press-enter="huiche"></a-input>
                        </a-form-item>
                        <a-form-item label="调机工资单">
                            <!-- <a-select popup-container="html"  :style="{ width: '200px' }" :loading="loading" @search="handleSearchDh" class="bacClass"
                            v-model="pageData.salaryCode" :filter-option="false" allow-search allow-clear
                            @focus="focusSelDh">
                            <a-option v-for="item in pageData.nameList1" :value="item">{{ item }}</a-option>
                        </a-select> -->
                            <a-input allow-clear :style="{ width: '200px' }" class="bacClass"
                                v-model="pageData.salaryCode" @press-enter="huiche"></a-input>
                        </a-form-item>
                        <a-form-item label="日期">
                            <a-date-picker  popup-container="html"  :style="{ width: '150px' }" class="bacClass" v-model="pageData.startDate"  @press-enter="huiche" />至
                            <a-date-picker  popup-container="html"  :style="{ width: '150px' }" class="bacClass" v-model="pageData.endDate"  @press-enter="huiche" />
                        </a-form-item>
                    </a-form>
                </div>
                <div class="my-tool-bar">
                    <Toolbar class="gesture" :items="['查询', '新增', '删除']" @add="addHandler" @del="deleteHandler"
                        @select="selectHandler">
                    </Toolbar>
                </div>
            </div>
            <div class="my-divisders">
                <a-divider orientation="center">
                    <icon-double-up v-if="headerShow" @click="headerShow = false" :strokeWidth="2" :size="18" />
                    <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
                </a-divider>
            </div>

        </template>
        <template #pageTabel>


              <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true" rowSelection="multiple" @grid-ready="gridReady" style="height:100%"
                :defaultColDef="defaultColDef" class='ag-theme-alpine' :rowData="table.dataList"
                :localeText="localeText1" :columnDefs="tc"></AgGridVuesCopys>

        </template>
        <paginationCopys :total="total" show-total show-jumper show-page-size @change="PageSize"
            @page-size-change="change1" style="justify-content: center" />
        <a-drawer ok-text='保存' cancel-text='关闭' :drawer-style="{ 'zIndex': 999 }" :mask-closable="false" :width="400"
            unmount-on-close popup-container=".arco-tabs-content" placement="bottom" :height="pageData.rHeight"
            :ok-loading="pageData.pageLoading" :visible="pageData.showAdd" @ok="sideOk"
            @cancel="pageData.showAdd = false">
            <template #title>
                {{ pageData.sideTitle }}
            </template>
            <!-- <a-space style="margin-bottom:10px;">
                <a-button type="primary" @click="addLine" size="mini">新增</a-button>
                <a-button type="primary" @click="delLine" size="mini">删除</a-button>
            </a-space> -->
            <a-table stripe :bordered="true" :columns="tableColumns1" size="mini" :loading="table.tableLoading"
                :data="pageData.list" rowKey="id">
                <template #unitPrice="{ record }">
                    <div style="width:100%;">
                        <a-select popup-container="html"  :loading="loading" @search="handleSearchCpj" class="bacClass"
                            v-model="record.unitPrice" :filter-option="false" allow-search allow-clear
                            @focus="focusSelCpj" @change="changeCpj(record, record.unitPrice)">
                            <a-option v-for="item in pageData.cpjList" :value="item.price">{{
                                item.price
                            }}</a-option>
                        </a-select>
                    </div>
                </template>
                <template #unit="{ record }">
                    <div style="width:100%;">
                        <a-select popup-container="html"  :loading="loading" class="bacClass" v-model="record.unit" allow-clear
                            @focus="getUnitList">
                            <a-option v-for="item in pageData.unitList" :value="item.detailName">{{
                                item.detailName
                            }}</a-option>
                        </a-select>
                    </div>
                </template>

            </a-table>
        </a-drawer>
        <a-modal v-model:visible="visible" title="选择拆纱单号" @cancel="handleCancel" :draggable="true">
            <a-form :model="pageData" :label-col-props="{ span: 6 }" :wrapper-col-props="{ span: 18 }">
                <a-form-item label="拆纱单号">
                    <a-select popup-container="html"  class="bacClass" v-model="pageData.adjustmentCode" multiple>
                        <a-option v-for="(item, index) in pageData.codeList" :value="item.id">
                            {{ item.adjustmentCode }}
                        </a-option>
                    </a-select>
                </a-form-item>
            </a-form>
            <template #footer>
                <a-button type="primary" size="small" @click="handleOk">确定</a-button>
            </template>
        </a-modal>

    </pageTabelLayout>
</template>

<script lang="ts">
import { post, get } from '@/api/http'
import { useTable, useRowKey, useTableColumn, usePagination, useRowSelection } from '@/hooks/table';
import emitter from "@/hooks/useEventBus";
import { ref, reactive, onMounted, toRefs } from 'vue'
import Toolbar from '@/components/Toolbar.vue';
import { Button, Form, Message, Modal } from '@arco-design/web-vue';
import { FormInstance } from '@arco-design/web-vue/es/form';
import { baseURL } from '../../../api/axios.config'
import axios from "axios";
import filedownload from 'js-file-download'
import usePermission from '@/store/modules/permission'
import PageTabelLayout from '@/components/pageTabelLayout.vue';
import MyTable from '@/components/MyTable';
import ButtonRenderer from '@/components/TableCellRenderer/ButtonRenderer';
import { template } from 'lodash';
import { setupGlobalComponent } from '@/layouts';
// 引入
;
import { localeText } from '@/api/aggridZw'

interface AdjustmentPartsList {
    "id": any,
    "unitPrice": any,
    "disassembleInfoId": any,
    "amount": any,
    "weightNum": any,
    "perCapitaPrice": any,
    "salaryCode": string | undefined,
    "empNames": string | undefined,
    "disassembleCode": string | undefined,
    "disassembleDate": string | undefined,
    "createName": string | undefined,
    "createTime": string | undefined,
    "updateName": string | undefined,
    "updateTime": string | undefined,
}

export default {
    name: "CheckInPartsList",

    setup() {
        const total = ref(0);
        const page = ref(1);
        const size = ref(10);
        function PageSize(val: any) {
            page.value = val
            doRefresh();
        }
        function change1(val: any) {
            size.value = val
            doRefresh();
        }
        const headerShow = ref<boolean>(true)

        function doRefresh() {

            pageData.pageLoading = true
            post({
                url: "pieceData/adjustmentSalary/getPage",
                data: {
                    page: page.value,
                    size: size.value,
                    deleteState: "0",
                    empName: pageData.empName,
                    salaryCode: pageData.salaryCode,
                    startDate: pageData.startDate,
                    endDate: pageData.endDate
                },
            })
                .then(({ data, code }: any) => {

                    if (code === 200) {

                        table.handleSuccess(data.list);

                        // 查询方法改

                        gridOption.value.setRowData(data.list)




                        total.value = data.total;
                    }
                })
                .catch(console.log).finally(() => {
                    pageData.pageLoading = false
                })
        }

        const { selectedRowKeys, onSelectionChange } = useRowSelection();
        const selectedRowKeys1 = useRowSelection();
        const pagination = usePagination(doRefresh);
        const table = useTable();
        const rowKey = useRowKey("id");
        const tableColumns = useTableColumn([
            {
                title: "调机工资单",
                key: "salaryCode",
                dataIndex: "salaryCode",
                width: 150
            },

            {
                title: "调机单",
                key: "adjustmentCode",
                dataIndex: "adjustmentCode",
                width: 150
            },
            {
                title: "机修类型",
                key: "maintainType",
                dataIndex: "maintainType",
                width: 150
            },
            {
                title: "机台号",
                key: "machineCode",
                dataIndex: "machineCode",
                width: 150
            },
            {
                title: "员工",
                key: "empNames",
                dataIndex: "empNames",
                width: 150
            },
            {
                title: "机修单价",
                key: "machineTypePrice",
                dataIndex: "machineTypePrice",
                width: 150
            },
            {
                title: "创建人",
                key: "createName",
                dataIndex: "createName",
                width: 150
            },
            {
                title: "创建时间",
                key: "createTime",
                dataIndex: "createTime",
                width: 200
            },

            {
                title: '操作',
                key: "id",
                slotName: 'act',
                width: 150, fixed: 'right'
            }
        ]);

        let tc: any[] = tableColumns.map((o) => {

            let obj = {
                headerName: o.title,
                field: o.key,
                pinned: o['fixed']
            }
            if (o.slotName === 'act') {
                obj['resizable'] = false
                obj['filter'] = false
                obj['sortable'] = false
                obj["lockPosition"] = "right"
                obj['width'] = '80px'
                obj['cellRenderer'] = {
                    template: `<a-tag color="#ff7d00" class="gesture"  @click="a">详情</a-tag>`,
                    setup(props: any) {
                        const a = () => {
                            editHandler(props.params.data)
                        }
                        return {
                            a
                        }
                    }

                }
            }

            return obj
        })

        let a = [{
            showRowGroup: 'hide_def',
            "headerName": "",
            "checkboxSelection": true,
            "headerCheckboxSelection": true,
            "pinned": "left",
            "width": 50,
            resizable: false,
            filter: false,
            sortable: false,
            minWidth: 50,
            maxWidth: 50,
            lockPosition: "left",
        }]
        tc = a.concat(tc)


        const tableColumns1 = useTableColumn([
            {
                title: "调机单",
                key: "adjustmentCode",
                dataIndex: "adjustmentCode",
                width: 150
            },

            {
                title: "机修类型",
                key: "maintainType",
                dataIndex: "maintainType",
                width: 150
            },
            {
                title: "机修单价",
                key: "machineTypePrice",
                dataIndex: "machineTypePrice",
                width: 150
            },
            {
                title: "机台号",
                key: "machineCode",
                dataIndex: "machineCode",
                width: 150,
            },
            {
                title: "员工",
                key: "empName",
                dataIndex: "empName",
                width: 150,
            },
            {
                title: "员工单价比例",
                key: "ratio",
                dataIndex: "ratio",
                width: 150
            },
            {
                title: "员工工资",
                key: "empPrice",
                dataIndex: "empPrice",
                width: 150
            },

        ]);

        const pageData = reactive<{
            showAdd: boolean,
            sideTitle: string,
            dropDownData: any,
            nameList: [],
            pageLoading: boolean,
            typeList: [],
            dropDownData1: any,
            rHeight: any,
            btnList: any[],
            isEdit: boolean,
            adjustmentCode: any[],
            dismantlingSheetNumberList: any[],
            addDataList: any[]
            list: any[]
            company: any
            firmList: any[]
            codeList: any[]
            cpjList: any[]
            unitList: any[]
            startDate: any
            endDate: any
            empName: any
            nameList1: any[]
            salaryCode: any
        }>({
            nameList: [],
            showAdd: false,
            sideTitle: '新增调机件资',
            dropDownData: "",
            pageLoading: false,
            typeList: [],
            dropDownData1: "",
            rHeight: 0,
            btnList: [],
            isEdit: false,
            adjustmentCode: [],
            dismantlingSheetNumberList: [],
            addDataList: [],
            list: [],
            company: null,
            firmList: [],
            codeList: [],
            cpjList: [],
            unitList: [],
            startDate: "",
            endDate: "",
            empName: '',
            nameList1: [],
            salaryCode: ""
        });

        interface gcType {
            id: any,
            company: any
        }

        //下拉框得到焦点
        const focusSel = () => {
            selCxAll({ "empName": "", deleteState: 0 });
        }
        //下拉数据
        const options = ref<any>(pageData.nameList);
        const loading = ref(false);
        const handleSearch = (value: any) => {
            if (value) {
                const ob = { empName: value, deleteState: 0 }
                loading.value = true;
                selCxAll(ob);
                options.value = pageData.nameList;
                loading.value = false;
            } else {
                options.value = []
            }
        };

        //下拉框查询
        function selCxAll(val: any) {
            post({
                url: "pieceData/adjustmentSalary/getEmpNameList",
                data: val
            }).then(({ data, code, message }: any) => {
                if (code === 200) {
                    pageData.nameList = data;
                } else {
                    Message.error({
                        content: message,
                        duration: 5000,
                    });
                }
            });
        }

        //下拉框得到焦点
        const focusSelDh = () => {
            selCxAllDh({ "salaryCode": "", deleteState: 0 });
        }
        //下拉数据
        const optionsDh = ref<any>(pageData.nameList1);
        const handleSearchDh = (value: any) => {
            if (value) {
                const ob = { salaryCode: value, deleteState: 0 }
                loading.value = true;
                selCxAllDh(ob);
                optionsDh.value = pageData.nameList1;
                loading.value = false;
            } else {
                optionsDh.value = []
            }
        };

        //下拉框查询
        function selCxAllDh(val: any) {
            post({
                url: "pieceData/adjustmentSalary/getSalaryCodeList",
                data: val
            }).then(({ data, code, message }: any) => {
                if (code === 200) {
                    pageData.nameList1 = data;
                } else {
                    Message.error({
                        content: message,
                        duration: 5000,
                    });
                }
            });
        }


        onMounted(() => {
            // 切换tap到本页面执行的方法
            // emitter.on("BrandInfo", () => {
            //     // selCxAll1({});
            //     doRefresh();
            // });
            pageData.rHeight = document.getElementsByClassName("arco-tabs-content")[0]?.clientHeight
            //弹出层的高
            if (pageData.rHeight !== undefined) {
                pageData.rHeight = pageData.rHeight - 100;
            }
            window.addEventListener('resize', () => {
                pageData.rHeight = document.getElementsByClassName("arco-tabs-content")[0]?.clientHeight
                //弹出层的高
                if (pageData.rHeight !== undefined) {
                    pageData.rHeight = pageData.rHeight - 100;
                }

            })
        });
        let cxbl = ""
        //查询
        const selectHandler = () => {

            pagination.page = 1
            cxbl = pageData.dropDownData
            doRefresh();
        }
        const queryData = reactive({
            clothType: ""
        });
        const addHandler = () => {
            pageData.adjustmentCode = []
            for (var key in dataForm) {
                dataForm[key] = undefined;
            }
            getAllCode("")
            visible.value = true;


        }
        const dataForm = reactive<AdjustmentPartsList>({
            "id": undefined,
            "unitPrice": undefined,
            "disassembleInfoId": undefined,
            "amount": undefined,
            "weightNum": undefined,
            "perCapitaPrice": undefined,
            "salaryCode": undefined,
            "empNames": undefined,
            "disassembleCode": undefined,
            "disassembleDate": undefined,
            "createName": undefined,
            "createTime": undefined,
            "updateName": undefined,
            "updateTime": undefined,
        })

        // 表格准备事件
        const gridOption = ref()
        const gridReady = (params: any) => {

            gridOption.value = params.api
        }



        let formRef = ref<FormInstance>()
        const sideOk = () => {

            pageData.pageLoading = true;
            if (pageData.sideTitle === "新增调机件资") {
                pageData.list.forEach(function (o: any) {
                    o['disassembleInfoId'] = o['id']
                })
                post({
                    url: "pieceData/adjustmentSalary/insertAdjustmentSalary",
                    data: pageData.list,
                }).then((res: any) => {
                    if (res.code === 200) {

                        pageData.showAdd = false;

                        Message.success({
                            content: "新增成功",
                            duration: 5000,
                        });
                    } else {
                        Message.error({
                            content: res.message,
                            duration: 5000,
                        });
                    }
                    doRefresh();
                }).finally(() => {
                    doRefresh();
                    pageData.pageLoading = false
                })
            } else {
                post({
                    url: "pieceData/disassembleSalary/update",
                    data: pageData.list,
                }).then((res: any) => {
                    if (res.code === 200) {

                        pageData.showAdd = false;
                        Message.success({
                            content: "修改成功",
                            duration: 5000,
                        });

                    } else {
                        Message.error({
                            content: res.message,
                            duration: 5000,
                        });
                    }

                }).finally(() => {

                    doRefresh();
                    pageData.pageLoading = false
                })
            }


        }
        const deleteHandler = () => {
            if (gridOption.value.getSelectedRows().length === 0) {
                Message.error('请先勾选');
                return
            }

            Modal.confirm({
                title: '系统提示',
                content: '确认删除选中的数据?',
                onOk() {
                    pageData.pageLoading = true;
                    post({
                        url: 'pieceData/disassembleSalary/updateState',
                        data: gridOption.value.getSelectedRows().map((o: any) => { return o.id })
                    }).then(({ code, data }: any) => {
                        if (code === 200) {
                            Message.success({
                                content: '删除成功',
                                duration: 5000
                            })
                            pagination.page = 1
                            doRefresh()

                        } else {
                            Message.error({
                                content: '删除失败',
                                duration: 5000
                            })
                        }

                    }).finally(() => {
                        pageData.pageLoading = false
                    });
                }
            })
        }

        let curobj = null
        const editHandler = (record: AdjustmentPartsList) => {
            curobj = record
            echoData(record.id)


            pageData.sideTitle = '详情'
            pageData.showAdd = true
        }
        //修改回显数据
        function echoData(id: any) {
            post({
                url: "pieceData/adjustmentSalary/getAdjustmentSalaryInfoById?id=" + id,
            }).then(({ data, code, message }: any) => {
                if (code === 200) {
                    pageData.list = data;

                } else {
                    Message.error({
                        content: message,
                        duration: 5000,
                    });
                }
            });
        }

        //下拉数据
        const options1 = ref<any>(pageData.typeList);
        const loading1 = ref(false);
        const handleSearch1 = (value: any) => {
            if (value) {

                const ob = {
                    key: value,
                    deleteState: 0
                }
                loading.value = true;
                selCxAll1(ob);
                options.value = pageData.typeList;
                loading.value = false;
            } else {
                options.value = []
            }
        };

        //下拉框查询 布料类型
        function selCxAll1(val: any) {
            post({
                url: "product/mercery/getAllMerceryName",
                data: val
            }).then(({ data, code }: any) => {
                if (code === 200) {

                    pageData.typeList = data;


                } else {
                    Message.error({
                        content: "查询失败！",
                        duration: 5000,
                    });
                }
            });
        }

        //下拉框得到焦点
        const focusSel1 = () => {
            selCxAll1({ "key": "" });
        }

        const defaultColDef = {
            sortable: true,
            resizable: true,
            filter: true,
            // flex: 1
        }
        //打开单号弹窗
        const visible = ref(false);
        const handleOk = () => {
            visible.value = false;
            //判断是否勾选了拆纱单
            if (pageData.adjustmentCode.length == 0) {
                Message.warning({
                    content: "请勾选拆纱单",
                    duration: 5000,
                });
                return
            }
            //根据多个调机单Id查询对应的员工详情
            post({
                url: "pieceData/adjustmentInfo/getEmpInfoByIdList",
                data: pageData.adjustmentCode
            }).then(({ data, code }: any) => {
                if (code === 200) {
                    pageData.list = data;
                    // //筛选出勾选单号数据
                    // pageData.list = pageData.codeList.filter(function (o: any) {
                    //     return pageData.adjustmentCode.includes(o['id'])
                    // })
                    pageData.showAdd = true
                    pageData.sideTitle = '新增调机件资'
                } else {
                    Message.error({
                        content: "查询失败！",
                        duration: 5000,
                    });
                }
            });

        };


        const handleCancel = () => {
            visible.value = false;
        }
        const localeText1: any = ref(localeText)
        let c = 0
        //成分添加一行 点击新增按钮
        const addLine = () => {
            //在这个数组前面添加一行
            pageData.list.unshift({
                "id": 'add' + (c++),
                "disassembleCode": "",
                "weightNum": 0,
                "amount": 0,
                "unitPrice": 0,
                "perCapitaPrice": 0,
                "salaryCode": "",
                "unit": "",
                "empNames ": "",
                "disassembleDate": "",

            })
        }
        //子表 删除
        const delLine = () => {

            if (selectedRowKeys1.selectedRowKeys.value.length === 0) {
                Message.error({
                    content: '请先勾选',
                    duration: 5000
                })
                return
            }
            pageData["list"] = pageData["list"].filter(function (o: any) {
                return selectedRowKeys1.selectedRowKeys.value.indexOf(o["id"]) === -1
            })

        }
        //查所有单号
        function getAllCode(val: any) {
            post({
                url: "pieceData/adjustmentInfo/getAdjustmentOrderInfo",
                data: {
                    "page": 1,
                    "size": 50,

                }
            }).then(({ data, code }: any) => {
                if (code === 200) {
                    pageData.codeList = data.list;
                } else {
                    Message.error({
                        content: "查询失败！",
                        duration: 5000,
                    });
                }
            });
        }
        //下拉框得到焦点
        const focusSelCpj = () => {
            selCxAllCpj({ "price": "" });
        }
        //下拉数据
        const optionsCpj = ref<any>(pageData.cpjList);
        const handleSearchCpj = (value: any) => {
            if (value) {
                const ob = { price: value }
                loading.value = true;
                selCxAllCpj(ob);
                optionsCpj.value = pageData.cpjList;
                loading.value = false;
            } else {
                optionsCpj.value = []
            }
        };

        //下拉框查询
        function selCxAllCpj(val: any) {
            post({
                url: "pieceData/transportPrice/getList",
                data: val
            }).then(({ data, code }: any) => {
                if (code === 200) {
                    pageData.cpjList = data
                } else {
                    Message.error({
                        content: "查询失败！",
                        duration: 5000,
                    });
                }
            });
        }
        //单价下拉框改变 金额算出 金额=重量*单价  个人工资=重量*单价 / 人数
        const changeCpj = (record: any, val: any) => {
            record.amount = (parseFloat(record.weightNum) * parseFloat(val)).toFixed(2)
            record.perCapitaPrice = (parseFloat(record.weightNum) * parseFloat(val) / parseFloat(record.peopleNum)).toFixed(2)
        }
        //获取单位下拉框
        function getUnitList() {
            post({
                url: 'dict/dictTypeDetail/getListByCodeType?codeType=17',

            }).then((res: any) => {
                if (res.code == 200) {
                    pageData.unitList = res.data
                }
            })
        }
        const huiche = () => {
            doRefresh()
        }
        return {
            huiche,
            getUnitList,
            changeCpj,
            focusSelCpj,
            optionsCpj,
            handleSearchCpj,
            delLine,
            addLine,
            visible,
            handleOk,
            handleCancel,
            localeText1,
            defaultColDef,
            tc,
            total,
            PageSize,
            change1,
            page,
            size,
            editHandler,
            deleteHandler,
            sideOk,
            formRef,
            dataForm,
            addHandler,
            selectedRowKeys,
            pagination,
            tableColumns,
            table,
            rowKey,
            pageData,
            queryData,
            selectHandler,
            options,
            loading,
            handleSearch,
            focusSel,
            options1,
            loading1,
            handleSearch1,
            focusSel1,
            headerShow,
            gridReady,
            s: selectedRowKeys1.selectedRowKeys,
            tableColumns1,
            optionsDh,
            handleSearchDh,
            focusSelDh,
        };
    },
    components: { Toolbar, PageTabelLayout,  }
}
</script>
<style scoped lang="less">
:deep(.ag-cell) {
    border-right: 1px solid #dde2eb;
}

:deep(.ag-header-cell) {
    border-right: 1px solid #dde2eb;
}

:deep(.ag-cell-value) {
    user-select: initial;
    -moz-user-select: text;
    -ms-user-select: text;
    -webkit-user-select: text;
}
</style>